﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibUsbDotNet.Main;
using LibUsbDotNet.WinUsb;
using LibUsbDotNet;

namespace Lipesin.MP710cmd
{
	class Program
	{
		private enum RequestType : byte
		{
			//libusb_request_recipient
			/** Device */
			LIBUSB_RECIPIENT_DEVICE = 0x00,

			/** Interface */
			LIBUSB_RECIPIENT_INTERFACE = 0x01,

			/** Endpoint */
			LIBUSB_RECIPIENT_ENDPOINT = 0x02,

			/** Other */
			LIBUSB_RECIPIENT_OTHER = 0x03,


			//libusb_request_type
			/** Standard */
			LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5),

			/** Class */
			LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5),

			/** Vendor */
			LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5),

			/** Reserved */
			LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5),

			//libusb_endpoint_direction
			/** In: device-to-host */
			LIBUSB_ENDPOINT_IN = 0x80,

			/** Out: host-to-device */
			LIBUSB_ENDPOINT_OUT = 0x00
		}
		static void Main(string[] args)
		{
			//args = new string[] { "4", "0" };
			if (args.Length < 2)
			{
				Console.WriteLine("usage:");
				Console.WriteLine("MP710cmd PORT LIGH");
				Console.WriteLine("where");
				Console.WriteLine("PORT = 0..15");
				Console.WriteLine("LIGHT = 0..128");
				return;
			}
			byte portNumber;
			byte value;
			if (!byte.TryParse(args[0], out portNumber) || portNumber < 0 || portNumber > 15)
			{
				Console.WriteLine("error: PORT must be in 0..15");
				return;
			}
			if (!byte.TryParse(args[1], out value) || value < 0 || value > 128)
			{
				Console.WriteLine("error: LIGH must be in 0..128");
				return;
			}

			UsbRegDeviceList list = WinUsbDevice.AllLibUsbDevices;
			UsbRegistry r = list.Find((registry) => registry.Vid == 0x16c0 && registry.Pid == 0x05df);
			if (r == null)
			{
				Console.WriteLine("Устройство не найдено.");
				return;
			}
			UsbDevice device = r.Device;
			IUsbInterface iusb;
			iusb = device as IUsbInterface;
			iusb.Open();
			bool opened = iusb.IsOpen;
			if (!opened)
			{
				Console.WriteLine("Устройство не открылось.");
				return;
			}
			byte[] buf = new byte[8];
			buf[0] = 0x63;
			buf[1] = portNumber;
			buf[2] = value;
			buf[3] = 0;
			buf[5] = 15;
			buf[7] = 15;
			int outLen;
			UsbSetupPacket packet = new UsbSetupPacket
				(
					Convert.ToByte(RequestType.LIBUSB_REQUEST_TYPE_CLASS | RequestType.LIBUSB_RECIPIENT_INTERFACE | RequestType.LIBUSB_ENDPOINT_OUT),
					0x9,
					0x300,
					0,
					8
				);
			bool success;
			int errorCount = 0;
			do
			{
				success = iusb.ControlTransfer(ref packet, buf, 8, out outLen);
				if (!success)
				{
					errorCount++;
					iusb.Close();
					iusb.Open();
				}
			} while (!success && errorCount < 3);
			if (!success)
			{
				Console.WriteLine("Запрос не прошёл.");
				return;
			}
		}
	}
}
